import cv2
import numpy as np


def detect_wrong_score_lines(image_path):
    # 读取图像
    img = cv2.imread(image_path)
    if img is None:
        print(f"无法读取图像: {image_path}")
        return

    # 转换为灰度图像
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 高斯模糊以减少噪声
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # 边缘检测，尝试调整Canny阈值
    edges = cv2.Canny(blurred, 30, 100)

    # 形态学操作：膨胀和腐蚀
    kernel = np.ones((3, 3), np.uint8)
    edges = cv2.dilate(edges, kernel, iterations=1)
    edges = cv2.erode(edges, kernel, iterations=1)

    # 查找轮廓
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 筛选轮廓
    min_area = 10  # 最小轮廓面积
    min_aspect_ratio = 0.1  # 最小长宽比
    max_aspect_ratio = 0.7  # 最大长宽比
    filtered_contours = []
    for contour in contours:
        area = cv2.contourArea(contour)
        if area < min_area:
            continue
        x, y, w, h = cv2.boundingRect(contour)
        aspect_ratio = float(w) / h if h != 0 else 0
        if min_aspect_ratio < aspect_ratio < max_aspect_ratio:
            filtered_contours.append(contour)

    # 绘制筛选后的轮廓
    cv2.drawContours(img, filtered_contours, -1, (0, 0, 255), 2)

    # 显示结果
    cv2.imshow('Detected Wrong Score Lines', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # 保存结果
    # result_path = 'result.jpg'
    # cv2.imwrite(result_path, img)
    # print(f"结果已保存到: {result_path}")

if __name__ == "__main__":
    image_path = 'score_red.png'  # 请替换为实际的图像路径
    detect_wrong_score_lines(image_path)
    